package com.gitee.wsl.data.recycler

import com.gitee.wsl.data.recycler.RecyclerPool.WithPool
import com.gitee.wsl.collections.deque.toDeque
import kotlin.jvm.Transient


/**
 * [RecyclerPool] implementation that uses
 * [ConcurrentLinkedDeque] for recycling instances.
 *
 *
 * Pool is unbounded: see [RecyclerPool] what this means.
 */
abstract class ConcurrentDequePoolBase<P : WithPool<P>>
protected constructor(serialization: Int) : StatefulImplBase<P>(serialization) {
    @Transient
    protected val pool  = mutableListOf<P>().toDeque()

    // // // Actual API implementation
    override fun acquirePooled(): P {
        return if (pool.isEmpty()) {
            createPooled()
        }else
            pool.removeLast()
    }

    override fun releasePooled(pooled: P) {
        pool.addLast(pooled)
    }

    override fun pooledCount(): Int {
        return pool.size
    }

    override fun clear(): Boolean {
        pool.clear()
        return true
    }

}

fun <P : WithPool<P>> RecyclerPool.Companion.concurrentDeque(serialization: Int,createPooled:()->P)
   = object :ConcurrentDequePoolBase<P>(serialization){
    override fun createPooled(): P = createPooled()
}